package com.common.base.utils

import android.os.CountDownTimer
import java.util.concurrent.TimeUnit

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2024/6/5
 *
 * 描述：倒计时定时器工具
 *
 * 修订历史：
 *
 */
class TimeCountUtil {
    private var listener: TimeCountListener? = null
    private var countDownTimer: CountDownTimer? = null
    private var offset = 0L

    constructor(second: Long) {
        createCountDownTimer(second * 1000L, 1000L)
    }

    constructor(millisInFuture: Long, countDownInterval: Long, timeUnit: TimeUnit) {
        val unit = timeUnit.toMillis(1L)
        createCountDownTimer(millisInFuture * unit, countDownInterval * unit)
    }

    fun setSecondOffset(offset: Long) {
        this.offset = offset * TimeUnit.SECONDS.toMillis(1L)
    }

    fun setUnitOffset(offset: Long, timeUnit: TimeUnit) {
        this.offset = offset * timeUnit.toMillis(1L)
    }
    fun setListener(listener: TimeCountListener?) {
        this.listener = listener
    }

    fun start() {
        countDownTimer?.start()
    }

    fun cancel() {
        countDownTimer?.cancel()
    }

    private fun createCountDownTimer(millisInFuture: Long, countDownInterval: Long) {
        countDownTimer = object : CountDownTimer(millisInFuture, countDownInterval) {
            override fun onTick(millisUntilFinished: Long) {
                var leftTime = millisUntilFinished - offset
                if (leftTime <= 0L) {
                    this.cancel()
                    listener?.onTimeFinish()
                } else if (listener != null) {
                    leftTime /= 1000L
                    if (listener is SecondCountListener) {
                        (listener as SecondCountListener?)?.onTimeCutDown(leftTime)
                    } else if (listener is DayCountListener) {
                        val second = (leftTime % 60L).toInt()
                        leftTime /= 60L
                        val minute = (leftTime % 60L).toInt()
                        leftTime /= 60L
                        val hour = (leftTime % 24L).toInt()
                        val day = (leftTime / 24L).toInt()
                        (listener as DayCountListener?)?.onTimeCutDown(day, hour, minute, second)
                    }
                }
            }

            override fun onFinish() {
                listener?.onTimeFinish()
            }
        }
    }

    interface TimeCountListener {
        fun onTimeFinish()
    }

    interface DayCountListener : TimeCountListener {
        fun onTimeCutDown(day: Int, hour: Int, minute: Int, second: Int)
    }

    interface SecondCountListener : TimeCountListener {
        fun onTimeCutDown(var1: Long)
    }
}